package org.rency.ues.domainservice.crypto.support;

import java.security.cert.X509Certificate;

import org.rency.common.utils.security.X509CertUtils;
import org.rency.ues.common.enums.EncryptType;
import org.rency.ues.domainservice.crypto.AbstractCryptor;
import org.rency.ues.domainservice.support.Certification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CMSRSACryptor extends AbstractCryptor {
	
	private static final Logger logger = LoggerFactory.getLogger(CMSRSACryptor.class);

	public CMSRSACryptor(EncryptType t) {
		super(t);
	}

	@Override
	public String encrypt(byte[] plainData, Object[] parameters) {
		if (parameters == null || parameters.length != 1) {
            logger.error("Invalid parameters.");
        }
        if (parameters[0] instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) parameters[0];
            try {
				return X509CertUtils.encryptCMS(plainData, cert);
			} catch (Exception e) {
				logger.error("encrypt data exception.",e);
				return null;
			}
        } else {
            logger.error("Invalid parameters.");
        }
        return null;
	}

	@Override
	public byte[] decrypt(String enData, Object[] parameters) {
		if (parameters == null || parameters.length != 1) {
            logger.error("Invalid parameters.");
        }
        if (parameters[0] instanceof Certification) {
            Certification certOld = (Certification) parameters[0];
            byte[] result = X509CertUtils.decryptCMS(enData, certOld.getCertificate(), certOld.getPrivateKey());
            return result;

        } else {
            logger.error("Invalid parameters.");
        }
        return null;
	}

}
